/*******************************************************************************
 * Copyright (c) 2013, 2014 EclipseSource and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    EclipseSource - initial API and implementation
 ******************************************************************************/
package org.apache.hop.ui.hopgui;

import java.nio.file.Files;
import java.nio.file.Paths;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.vfs2.FileObject;
import org.apache.hop.core.database.RunPython;
import org.apache.hop.ui.core.PropsUi;
import org.apache.hop.ui.core.dialog.BaseDialog;
import org.apache.hop.ui.core.gui.GuiResource;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class ChatRag extends Dialog {
  private static final Class<?> PKG =
      org.apache.hop.ui.core.dialog.ShowBrowserDialog.class; // For Translator

  private static final String[] WIDGETS =
      new String[] {"参考当前文件生成内容", "参考当前文件夹下生成内容", "参考系统帮助", "不参考任何文件"};
  private final String dialogTitle;
  GridData gdAn;
  private Text question;
  private Text answer;
  private Combo widgetCombo;
  private Shell shell;
  private FileObject fileObj;
  private boolean isFile = false;
  private String user_prompt = "";

  public ChatRag(Shell parent, String dialogTitle) {
    super(parent, SWT.NONE);
    this.dialogTitle = dialogTitle;
  }

  public void open() {
    Shell parent = getParent();
    shell = new Shell(parent, SWT.MAX | SWT.RESIZE);
    shell.setImage(GuiResource.getInstance().getImageHopUi());
    PropsUi.setLook(shell);
    shell.setText(dialogTitle);
    createStyleControls(shell);
    BaseDialog.defaultShellHandling(shell, c -> ok(), c -> ok());
  }

  public void dispose() {
    shell.dispose();
  }

  private void ok() {
    dispose();
  }

  /**
   * 设置文件
   *
   * @param fileObj 文件对象
   */
  public void setFileObj(FileObject fileObj) {
    this.fileObj = fileObj;
    try {
      isFile = fileObj.isFile();
      if (!isFile) return;
      String filePath = fileObj.getPath().toString();
      this.user_prompt = new String(Files.readAllBytes(Paths.get(filePath)));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  protected void createStyleControls(Shell parent) {
    parent.setLayout(new GridLayout(1, false));
    Label label = new Label(parent, SWT.NONE);
    // label.setLayoutData( new GridData( 150, 25 ) );
    label.setText("大模型查找类型");
    widgetCombo = new Combo(parent, SWT.DROP_DOWN | SWT.READ_ONLY);
    widgetCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    // gridData.horizontalSpan = 2;
    widgetCombo.setItems(WIDGETS);
    if (isFile) widgetCombo.select(0);
    else widgetCombo.select(1);

    Composite div = new Composite(parent, SWT.NONE);
    GridLayout gl = new GridLayout(2, false);
    gl.marginWidth = 0;
    // gl.horizontalSpacing  = 0;
    div.setLayout(gl);
    GridData divGd = new GridData(GridData.FILL_HORIZONTAL);
    div.setLayoutData(divGd);

    question = new Text(div, SWT.MULTI | SWT.BORDER);
    GridData textData = new GridData(GridData.FILL_HORIZONTAL);
    textData.horizontalIndent = GridData.BEGINNING;
    textData.heightHint = 42;
    question.setLayoutData(textData);
    question.setText("问题:");
    // add by bzm:从文件读取base64的prompt提示词
    if (!StringUtils.isEmpty(this.user_prompt)) question.setText(this.user_prompt);
    question.setToolTipText("输入查找的内容");

    Button button = new Button(div, SWT.PUSH);
    button.setText("内容查找");
    GridData gridData = new GridData(GridData.FILL_VERTICAL);
    button.setLayoutData(gridData);
    button.addListener(
        SWT.Selection,
        new Listener() {
          @Override
          public void handleEvent(Event event) {
            handleSetBtn();
          }
        });

    answer = new Text(parent, SWT.MULTI | SWT.BORDER);
    gdAn = new GridData(GridData.FILL_BOTH);
    gdAn.heightHint = 300;
    gdAn.grabExcessVerticalSpace = true;
    answer.setLayoutData(gdAn);
    answer.setToolTipText("大模型回答的结果");
    answer.setText("回答内容:");
    answer.setFont(new Font(answer.getDisplay(), "Courier New", 12, SWT.NORMAL));
  }

  /** 处理生成按钮的事件 */
  private void handleSetBtn() {
    try {
      answer.setText("大模型思考中......");
      String dir = fileObj.getPath().toString();
      System.out.println("dir=" + dir);
      String ret = "";
      switch (widgetCombo.getSelectionIndex()) {
        case 0: // "参考当前文件生成内容"
          if (isFile) {
            ret = RunPython.runFileChat(dir, question.getText());
          } else {
            MessageBox box = new MessageBox(shell);
            box.setMessage("请选择一个文件");
            box.open();
            ret = "请选择一个文件";
          }
          break;
        case 1: // "参考当前文件夹下的文件生成内容"
          if (isFile) {
            MessageBox box = new MessageBox(shell);
            box.setMessage("请选择一个文件夹");
            box.open();
            ret = "请选择一个文件夹";
          } else {
            ret = RunPython.runDirChat(dir, question.getText());
          }
          break;
        case 2: // , "参考系统默认的帮助知识库"
          ret = RunPython.runDirChat("systemdochelp12345678", question.getText());
          break;
        case 3: // "不参考任何文件"
          ret = RunPython.runFileChat("", question.getText());
          break;
      }
      answer.setText(ret);
    } catch (Exception e) {
      answer.setText("生成失败:" + e);
    }
  }
}
